//
//  HTTPTool.m
//  Chat
//
//  Created by Wangchengshan on 15/10/26.
//  Copyright (c) 2015年 Wangchengshan. All rights reserved.
//

#import "HTTPTool.h"
#import "AFNetworking.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#import<CommonCrypto/CommonDigest.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "SAMKeychain.h"
#import "SAMKeychainQuery.h"

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"

@implementation HTTPTool

/**
 *  GET请求
 */
+ (void)GET:(NSString *)url parameters:(id)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.0f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"image/png",@"image/jpeg", nil];;
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *token = [userDefault objectForKey:@"Token"];
    NSLog(@"token = %@",token);
    if (token) {
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"Token"];
        
    }    
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        
        NSDictionary *responseDirt = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                     options:NSJSONReadingMutableContainers
                                                                       error:nil];
        //Token  授权过期  同意跳转到登录页面-2token不正确
        if (responseDirt && ([[responseDirt objectForKey:@"Code"] intValue] == 102 || [[responseDirt objectForKey:@"Code"] intValue] == -2)) {
            
            [kUserDefault removeObjectForKey:@"isLogin"];
            
            
            
            return ;
        }
        
        success([self removeNSNullObjectFromeData:responseDirt]);
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        
//        NSLog(@"Error: %@", error);
        
        if (failure) {
            
            if (error.code == 401) {
                
                //[self alertActionStyleDestructive];
                
                return ;
            }
            
            [MBProgressHUD showText:@"网络异常"];
            
            failure(error);
        }
        
    }];
    
}

/**
 *  POST请求
 */
+ (void)POST:(NSString *)url parameters:(id)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10.0f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];;
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];    
    NSString *token = [userDefault objectForKey:@"Token"];
    if (token) {
        
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"bearer %@",token] forHTTPHeaderField:@"Authorization"];
    }
    
    //图片数据移除
    NSData *imageData = [params objectForKey:@"File"];
    [params removeObjectForKey:@"File"];
    
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //如果有图片的话就上传图片
        if (imageData) {
            
            [formData appendPartWithFileData:imageData name:@"File" fileName:[NSString stringWithFormat:@"%@.png",[self getCurrentTimestamp]] mimeType:@"image/png"];
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDirt = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                     options:NSJSONReadingMutableContainers
                                                                       error:nil];
        
        
        //Token  授权过期  同意跳转到登录页面-2token不正确
        if (responseDirt && ([[responseDirt objectForKey:@"Code"] intValue] == 102 || [[responseDirt objectForKey:@"Code"] intValue] == -2)) {
            
            [kUserDefault removeObjectForKey:@"isLogin"];
            
            
            
            return ;
        }
        
        //登录异常 或者被封号
        if ([[responseDirt objectForKey:@"Code"] intValue] == 607) {
            
            success([self removeNSNullObjectFromeData:responseDirt]);
            
            //[self alertActionStyleDestructive];
            
            return ;
        }
        else{
        
            success([self removeNSNullObjectFromeData:responseDirt]);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            
            failure(error);
        }
    }];
}

+ (void)GETRaw:(NSString *)url parameters:(id)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.timeoutInterval= 20;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *token = [userDefault objectForKey:@"Token"];
    [request setValue:token forHTTPHeaderField:@"Authorization"];
    NSData *body = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
    // 设置body
    [request setHTTPMethod:@"GET"];
    [request setHTTPBody:body];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",
                                                 nil];
    manager.responseSerializer = responseSerializer;
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            
            NSDictionary *responseDirt = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                         options:NSJSONReadingMutableContainers
                                                                           error:nil];
            
            //Token  授权过期  同意跳转到登录页面-2token不正确
            if (responseDirt && ([[responseDirt objectForKey:@"Code"] intValue] == 102 || [[responseDirt objectForKey:@"Code"] intValue] == -2)) {
                
                [kUserDefault removeObjectForKey:@"isLogin"];
                
                
            }
            
            success([self removeNSNullObjectFromeData:responseDirt]);
            
        } else {
            failure(error);
        }
    }] resume];
}

+ (void)POSTRaw:(NSString *)url parameters:(id)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.timeoutInterval= 20;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *token = [userDefault objectForKey:@"Token"];
    [request setValue:token forHTTPHeaderField:@"Token"];
    NSData *body = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
    // 设置body
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:body];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",
                                                 nil];
    manager.responseSerializer = responseSerializer;
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            
            NSDictionary *responseDirt = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                         options:NSJSONReadingMutableContainers
                                                                           error:nil];
            
            //Token  授权过期  同意跳转到登录页面-2token不正确
            if (responseDirt && ([[responseDirt objectForKey:@"Code"] intValue] == 102 || [[responseDirt objectForKey:@"Code"] intValue] == -2)) {
                
                [kUserDefault removeObjectForKey:@"isLogin"];
                
//                UserNavigationController *nav = [[UserNavigationController alloc] initWithRootViewController:[[LoginViewController alloc] init]];
//                [UIApplication sharedApplication].keyWindow.rootViewController = nil; //
//
//                [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                
                return ;
            }
            
            success([self removeNSNullObjectFromeData:responseDirt]);
            
        } else {
            
            failure(error);
            
            [MBProgressHUD showText:@"网络异常"];
        }
    }] resume];
}


//递归算法，去掉返回数据当中的所有NSNull型的数据
+ (id)removeNSNullObjectFromeData:(id)data {
    
    if ([data isKindOfClass:[NSDictionary class]]) {
        
        NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
        [data enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { if ([obj isKindOfClass:[NSNull class]]) {
            //将NSNull型的数据换成空字符串@""
            [resultDic setValue:@"" forKey:key];
            
        }else {
            //如果是非NSNull型的数据进入递归
            obj = [self removeNSNullObjectFromeData:obj];
            [resultDic setValue:obj forKey:key];
            
        }
            
        }];
        return resultDic;
        
    }else if ([data isKindOfClass:[NSArray class]]) {
        
        NSMutableArray *resultArr = [NSMutableArray array];
        [data enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { if ([obj isKindOfClass:[NSNull class]]) {
            //将NSNull型的数据换成空字符串@""
            [resultArr addObject:@""];
            
        }else {
            //如果是非NSNull型的数据进入递归
            obj = [self removeNSNullObjectFromeData:obj];
            [resultArr addObject:obj];
            
        }
            
        }];
        
        return resultArr;
        
    }else {
        return data;
        
    }

}

/**
 *  检测用户网络状态
 */
+ (void)startMonitoringWithChangeBlock:(void (^)(AFNetworkReachabilityStatus))block
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (block) {
            block(status);
        }
    }];
    [manager startMonitoring];
}

/**
 *  获取当前设备的IP地址
 */
+ (NSString *)getIPAddress:(BOOL)preferIPv4
{
    NSArray *searchArray = preferIPv4 ?
    @[ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
    @[ IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
    
    NSDictionary *addresses = [self getIPAddresses];
    //NSLog(@"addresses: %@", addresses);
    
    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
     {
         address = addresses[key];
         if(address) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}

+ (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) || (interface->ifa_flags & IFF_LOOPBACK)) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                char addrBuf[INET6_ADDRSTRLEN];
                if(inet_ntop(addr->sin_family, &addr->sin_addr, addrBuf, sizeof(addrBuf))) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, addr->sin_family == AF_INET ? IP_ADDR_IPv4 : IP_ADDR_IPv6];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    
    // The dictionary keys have the form "interface" "/" "ipv4 or ipv6"
    return [addresses count] ? addresses : nil;
}


+ (void)showNetworkActivityIndicator:(BOOL)open
{
//    [AFNetworkActivityIndicatorManager sharedManager].enabled = open;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+(NSString *)getSign:(NSMutableDictionary *)params{

    NSString *sign = @"";
    
    //[params setObject:@"eJx1jkFPgzAYhu-8iqZnoy2UAiYeyMI2cEsmbovxQmop" forKey:@"key"];
    
    NSArray *keyArray = [[params allKeys] sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                    
        return [obj1 compare:obj2]; //升序
        
    }];
    
    for (NSString *key in keyArray) {
        
        NSString *value = [params objectForKey:key];
        
        if ([key isEqualToString:@"image"] || [key isEqualToString:@"voice"] || [key isEqualToString:@"album"] || [value isEmptyString]) {
            
            continue;
        }
        
        sign = [NSString stringWithFormat:@"%@%@=%@&",sign,key,value];
    }
    
    sign = [NSString stringWithFormat:@"%@key=1e20d438-d0d8-4e0a-8c52-71dc09a7384e",sign];
    
    sign = [self md5:sign];
    
    sign = [sign uppercaseString];
    
    return sign;
}


+ (NSString *) md5:(NSString *) input {
    
    const char *cStr = [input UTF8String];
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
    
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return  output;
    
}

+(NSString *)getCurrentTimestamp{
    
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] * 1000;

    NSString *timeString = [NSString stringWithFormat:@"%0.f", interval];//转为字符型

//    InitHelper *helper = [InitHelper shareHelper];
//
//    long serviceTime = helper.serverTime;

    //转为字符型
//    NSString *returnTime = [NSString stringWithFormat:@"%0lld", [timeString longLongValue] + serviceTime];

    NSLog(@"timeString = %@",timeString);

    return timeString;
}


+ (NSString *)getMacAddress
{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1/n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    
    //    NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    
    NSLog(@"outString:%@", outstring);
    
    free(buf);
    
    return [outstring uppercaseString];
}

+(NSString *)appleIFA {
    
    NSString *ifa = nil;
    Class ASIdentifierManagerClass = NSClassFromString(@"ASIdentifierManager");
    if (ASIdentifierManagerClass) { // a dynamic way of checking if AdSupport.framework is available
        SEL sharedManagerSelector = NSSelectorFromString(@"sharedManager");
        id sharedManager = ((id (*)(id, SEL))[ASIdentifierManagerClass methodForSelector:sharedManagerSelector])(ASIdentifierManagerClass, sharedManagerSelector);
        SEL advertisingIdentifierSelector = NSSelectorFromString(@"advertisingIdentifier");
        NSUUID *advertisingIdentifier = ((NSUUID* (*)(id, SEL))[sharedManager methodForSelector:advertisingIdentifierSelector])(sharedManager, advertisingIdentifierSelector);
        ifa = [advertisingIdentifier UUIDString];
    }
    
    NSLog(@"ifa = %@",ifa);
    
    return ifa;
}

+(NSString *)getUniqueDeviceIdentifierAsString
{
    NSString *appName=[[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey];
    
    NSString *strApplicationUUID =  [SAMKeychain passwordForService:appName account:@"incoding"];
    if (strApplicationUUID == nil)
    {
        strApplicationUUID  = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        
        NSError *error = nil;
        SAMKeychainQuery *query = [[SAMKeychainQuery alloc] init];
        query.service = appName;
        query.account = @"incoding";
        query.password = strApplicationUUID;
        query.synchronizationMode = SAMKeychainQuerySynchronizationModeNo;
        [query save:&error];
        
    }
    
    NSLog(@"strApplicationUUID  = = %@",strApplicationUUID);
    
    return strApplicationUUID;
}

+(NSString *)getUniqueDeviceIdentifierAsString1
{
    NSString *appName=[[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey];
    
    NSString *strApplicationUUID =  [SAMKeychain passwordForService:appName account:@"incoding1"];
    if (strApplicationUUID == nil)
    {
        strApplicationUUID  = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        
        NSError *error = nil;
        SAMKeychainQuery *query = [[SAMKeychainQuery alloc] init];
        query.service = appName;
        query.account = @"incoding1";
        query.password = strApplicationUUID;
        query.synchronizationMode = SAMKeychainQuerySynchronizationModeNo;
        [query save:&error];
        
    }
    
    return  [self md5:strApplicationUUID];
}

@end
